package com.googlecode.yonggemovie.ui;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.yonggemovie.utils.Messages;
import com.googlecode.yonggemovie.utils.SwingWorker;
import com.googlecode.yonggemovie.utils.UIUtils;
import com.googlecode.yonggemovie.utils.db.Database;
import com.googlecode.yonggemovie.widgets.imagelist.ImageList;
import com.googlecode.yonggemovie.widgets.imagelist.ImageListData;
import com.googlecode.yonggemovie.widgets.imageviewer.ImageInfo;
import com.googlecode.yonggemovie.widgets.imageviewer.ImagePreviewButton;
import com.googlecode.yonggemovie.widgets.imageviewer.ImageViewerPanel;
import com.googlecode.yonggemovie.widgets.player.PlayerPanel;


public class MainFrame extends javax.swing.JFrame {
	
	private static final Log log = LogFactory.getLog(MainFrame.class);
	
	private JMenuItem helpMenuItem;
	private JSeparator jSeparator2;
	private JMenuItem updateMenuItem1;
	private JSeparator jSeparator1;
	private JMenu jMenu5;
	private JTabbedPane leftTabbedPane1;
	private JSplitPane jSplitPane1;
	private ImageList movieTypeList;
	private JPanel jPanel4;
	private JPanel jPanel3;
	private JPanel jPanel2;
	private ImageViewerPanel imagePanel;
	private JPanel rightPanel;
	private JPanel jPanel1;
	private JMenuItem jMenuItem6;
	private JMenuItem jMenuItem5;
	private JMenu jMenu6;
	private JMenuItem jMenuItem4;
	private JMenuItem jMenuItem3;
	private JMenu jMenu2;
	private JMenuItem jMenuItem2;
	private JMenuItem jMenuItem1;
	private JMenu jMenu1;
	private JMenuItem childtypeMenuItem1;
	private JMenuItem parentMenuItem1;
	private JMenuItem aboutMenuItem1;
	private JMenu tooMenu;
	private JMenu jMenu4;
	private JMenuItem exitMenuItem;
	private JButton addMovieBtn;
	private JButton addTypeBtn;
	private JButton addCatalogBtn;
	private JToolBar jToolBar1;
	private JPanel searchPanel;
	private JButton jButton2;
	private JButton jButton1;
	private JTextField searchTextField;
	private JComboBox jComboBox1;
	private JMenu jMenu3;
	private JMenuBar jMenuBar1;

	private PlayerPanel playerPanel;
	
	private Thread loadImageThread;
	
	private SystemTray systemTray;
	private TrayIcon trayIcon;
	
	private static final String IMAGE_PATH = "/com/googlecode/yonggemovie/resources/images/";
	
	
	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SplashSetting.init();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				LookAndFeelSetting.init();
				MainFrame inst = new MainFrame();
				inst.initSystemTray();
				//最大化
				inst.setExtendedState(JFrame.MAXIMIZED_BOTH);
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public MainFrame() {
		super();
		initGUI();
	}
	
	private void initSystemTray() {
		if(!SystemTray.isSupported()) {
			log.error("SystemTray is not supported");
			return;
		}
		systemTray = SystemTray.getSystemTray();
		trayIcon = new TrayIcon(UIUtils.createImageIcon(IMAGE_PATH+"clapperboard-16-16.PNG").getImage());
		trayIcon.setToolTip("有个电影");
		PopupMenu popupMenu = new PopupMenu();
		MenuItem aboutItem = new MenuItem("About");
		MenuItem exitItem = new MenuItem("Exit");
		popupMenu.add(aboutItem);
		popupMenu.addSeparator();
		popupMenu.add(exitItem);
		trayIcon.setPopupMenu(popupMenu);
		
		try {
			systemTray.add(trayIcon);
		} catch (AWTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				exit();
			}	
		});
		
		trayIcon.addMouseListener(new MouseAdapter(){
			
			public void mouseClicked(MouseEvent e) {
				if(SwingUtilities.isLeftMouseButton(e)) {
					setExtendedState(JFrame.MAXIMIZED_BOTH);
					setVisible(true);
					//systemTray.remove(trayIcon);
				}
			}		
		});
		
		
	}
	
	private void initPresentation() {
		this.setIconImage(UIUtils.createImageIcon(IMAGE_PATH+"clapperboard.png").getImage());
		this.setTitle("有个电影");
	}
	
	
	private void initGUI() {
		try {
			initPresentation();
			{
				//注意：当使用系统托盘时，这里不能设置成WindowConstants.EXIT_ON_CLOSE，否则关闭窗口就销毁窗口了。
				this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
				this.addWindowListener(new WindowAdapter() {
					public void windowClosing(WindowEvent evt) {
						thisWindowClosed(evt);
					}
				});
			}
			{
				jPanel1 = new JPanel();
				BorderLayout jPanel1Layout = new BorderLayout();
				jPanel1.setLayout(jPanel1Layout);
				getContentPane().add(jPanel1, BorderLayout.CENTER);
				jPanel1.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				{
					jSplitPane1 = new JSplitPane();
					jPanel1.add(jSplitPane1, BorderLayout.CENTER);
					jSplitPane1.setOneTouchExpandable(true);
					{
						leftTabbedPane1 = new JTabbedPane();
						jSplitPane1.add(leftTabbedPane1, JSplitPane.LEFT);
						leftTabbedPane1.setPreferredSize(new java.awt.Dimension(154, 374));
						leftTabbedPane1.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
						leftTabbedPane1.setTabPlacement(JTabbedPane.LEFT);
						{
							jPanel2 = new JPanel();
							BorderLayout jPanel2Layout = new BorderLayout();
							jPanel2.setLayout(jPanel2Layout);
							leftTabbedPane1.addTab(Messages.getString("MainFrame.moiveType"), null, jPanel2, null); //$NON-NLS-1$
							jPanel2.setPreferredSize(new java.awt.Dimension(105, 302));
							{
								
								movieTypeList = new ImageList(getMovieTypesBy());
								jPanel2.add(movieTypeList, BorderLayout.CENTER);
								movieTypeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
							}
						}
						{
							jPanel3 = new JPanel();
							leftTabbedPane1.addTab(Messages.getString("MainFrame.award"), null, jPanel3, null); //$NON-NLS-1$
						}
						{
							jPanel4 = new JPanel();
							leftTabbedPane1.addTab(Messages.getString("MainFrame.district"), null, jPanel4, null); //$NON-NLS-1$
						}
					}
					{
						rightPanel = new JPanel();
						BorderLayout rightPanelLayout = new BorderLayout();
						rightPanel.setLayout(rightPanelLayout);
						jSplitPane1.add(rightPanel, JSplitPane.RIGHT);
						rightPanel.setPreferredSize(new java.awt.Dimension(113, 374));
						{
							searchPanel = new JPanel();
							FlowLayout searchPanelLayout = new FlowLayout();
							searchPanel.setLayout(searchPanelLayout);
							rightPanel.add(searchPanel, BorderLayout.NORTH);
							searchPanel.setPreferredSize(new java.awt.Dimension(712, 39));
							{
								ComboBoxModel jComboBox1Model = 
									new DefaultComboBoxModel(
											new String[] { Messages.getString("MainFrame.moive"), Messages.getString("MainFrame.actor"),Messages.getString("MainFrame.director") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
											jComboBox1 = new JComboBox();
											searchPanel.add(jComboBox1);
											jComboBox1.setModel(jComboBox1Model);
											jComboBox1.setPreferredSize(new java.awt.Dimension(54, 22));
							}
							{
								searchTextField = new JTextField();
								searchPanel.add(searchTextField);
								searchTextField.setPreferredSize(new java.awt.Dimension(211, 22));
							}
							{
								jButton1 = new JButton();
								searchPanel.add(jButton1);
								jButton1.setIcon(UIUtils.createImageIcon(IMAGE_PATH+"find.png"));
							}
							{
								jButton2 = new JButton();
								searchPanel.add(jButton2);
								jButton2.setIcon(UIUtils.createImageIcon(IMAGE_PATH+"advance.png"));
							}
						}
						{
							imagePanel = new ImageViewerPanel();
							//TODO:临时显示
							loadImages(imagePanel);
							rightPanel.add(imagePanel, BorderLayout.CENTER);
							imagePanel.setPreferredSize(new java.awt.Dimension(712, 219));
						}
					}
				}
			}

			jToolBar1 = new JToolBar();
			getContentPane().add(jToolBar1, BorderLayout.NORTH);
			jToolBar1.setFloatable(false);
			jToolBar1.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));

			addCatalogBtn = new JButton();
			jToolBar1.add(addCatalogBtn);
			addCatalogBtn.setIcon(UIUtils.createImageIcon("/com/googlecode/yonggemovie/resources/images/add.png"));
			addCatalogBtn.setToolTipText("add catalog");
			
			addTypeBtn = new JButton();
			jToolBar1.add(addTypeBtn);
			addTypeBtn.setIcon(UIUtils.createImageIcon("/com/googlecode/yonggemovie/resources/images/add.png"));
			addTypeBtn.setToolTipText("add movie type");

			addMovieBtn = new JButton();
			jToolBar1.add(addMovieBtn);
			addMovieBtn.setIcon(UIUtils.createImageIcon("/com/googlecode/yonggemovie/resources/images/add.png"));
			addMovieBtn.setToolTipText("add movie");

			this.setSize(886, 435);
			{
				jMenuBar1 = new JMenuBar();
//				jMenuBar1.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE);
//				jMenuBar1.putClientProperty(PlasticLookAndFeel.IS_3D_KEY, Boolean.FALSE);
				setJMenuBar(jMenuBar1);
				jMenuBar1.setBorder(BorderFactory.createEmptyBorder(0, 2, 1, 2));
				{
					jMenu3 = new JMenu();
					jMenuBar1.add(jMenu3);
					jMenu3.setText(Messages.getString("MainFrame.file")); //$NON-NLS-1$
					{
						exitMenuItem = new JMenuItem();
						jMenu3.add(exitMenuItem);
						exitMenuItem.setText(Messages.getString("MainFrame.quit")); //$NON-NLS-1$
						exitMenuItem.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								exit();
							}
						});
					}
				}
				{
					jMenu4 = new JMenu();
					jMenuBar1.add(jMenu4);
					jMenu4.setText(Messages.getString("MainFrame.view")); //$NON-NLS-1$
					{
						jMenu1 = new JMenu();
						jMenu4.add(jMenu1);
						jMenu1.setText(Messages.getString("MainFrame.layout")); //$NON-NLS-1$
						{
							jMenuItem1 = new JMenuItem();
							jMenu1.add(jMenuItem1);
							jMenuItem1.setText(Messages.getString("MainFrame.layout1")); //$NON-NLS-1$
						}
						{
							jMenuItem2 = new JMenuItem();
							jMenu1.add(jMenuItem2);
							jMenuItem2.setText(Messages.getString("MainFrame.layout2")); //$NON-NLS-1$
						}
					}
					{
						jMenu2 = new JMenu();
						jMenu4.add(jMenu2);
						jMenu2.setText(Messages.getString("MainFrame.skin")); //$NON-NLS-1$
						{
							jMenuItem3 = new JMenuItem();
							jMenu2.add(jMenuItem3);
							jMenuItem3.setText(Messages.getString("MainFrame.skin1")); //$NON-NLS-1$
						}
						{
							jMenuItem4 = new JMenuItem();
							jMenu2.add(jMenuItem4);
							jMenuItem4.setText(Messages.getString("MainFrame.skin2")); //$NON-NLS-1$
						}
					}
					{
						jMenu6 = new JMenu();
						jMenu4.add(jMenu6);
						jMenu6.setText(Messages.getString("MainFrame.language")); //$NON-NLS-1$
						{
							jMenuItem5 = new JMenuItem();
							jMenu6.add(jMenuItem5);
							jMenuItem5.setText(Messages.getString("MainFrame.chinese")); //$NON-NLS-1$
						}
						{
							jMenuItem6 = new JMenuItem();
							jMenu6.add(jMenuItem6);
							jMenuItem6.setText(Messages.getString("MainFrame.english")); //$NON-NLS-1$
						}
					}
				}
				{
					tooMenu = new JMenu();
					jMenuBar1.add(tooMenu);
					tooMenu.setText(Messages.getString("MainFrame.tool")); //$NON-NLS-1$
					{
						parentMenuItem1 = new JMenuItem();
						tooMenu.add(parentMenuItem1);
						parentMenuItem1.setText(Messages.getString("MainFrame.addparent")); //$NON-NLS-1$
					}
					{
						childtypeMenuItem1 = new JMenuItem();
						tooMenu.add(childtypeMenuItem1);
						childtypeMenuItem1.setText(Messages.getString("MainFrame.addsub")); //$NON-NLS-1$
					}
				}
				{
					jMenu5 = new JMenu();
					jMenuBar1.add(jMenu5);
					jMenu5.setText(Messages.getString("MainFrame.help")); //$NON-NLS-1$
					{
						helpMenuItem = new JMenuItem();
						jMenu5.add(helpMenuItem);
						helpMenuItem.setText(Messages.getString("MainFrame.content")); //$NON-NLS-1$
					}
					{
						jSeparator1 = new JSeparator();
						jMenu5.add(jSeparator1);
					}
					{
						updateMenuItem1 = new JMenuItem();
						jMenu5.add(updateMenuItem1);
						updateMenuItem1.setText(Messages.getString("MainFrame.checkupdate")); //$NON-NLS-1$
					}
					{
						jSeparator2 = new JSeparator();
						jMenu5.add(jSeparator2);
					}
					{
						aboutMenuItem1 = new JMenuItem();
						jMenu5.add(aboutMenuItem1);
						aboutMenuItem1.setText(Messages.getString("MainFrame.about")); //$NON-NLS-1$
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 这里模拟数据，实际从dao取
	private List<ImageListData> getMovieTypesBy() {
		List<ImageListData> movieTypes = new ArrayList<ImageListData>();
		String[] movieTypeArr = new String[] { 
				Messages.getString("MainFrame.actionType"), 
				Messages.getString("MainFrame.comedyType"), 
				Messages.getString("MainFrame.lovestoryType"), 
				Messages.getString("MainFrame.fictionType"), 
				Messages.getString("MainFrame.horrorType"), 
				Messages.getString("MainFrame.dramaType") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
		
		for(int i=0;i<movieTypeArr.length;i++) {
			ImageListData imageData = new ImageListData(String.valueOf(i),movieTypeArr[i]);
			if(i%2 == 0) {
				imageData.setIcon(UIUtils.createImageIcon(IMAGE_PATH+"red_light.png"));
			}else {
				imageData.setIcon(UIUtils.createImageIcon(IMAGE_PATH+"yellow_light.png"));
			}
			movieTypes.add(imageData);
		}
			
		return movieTypes;
	}
	
	
	// 这里模拟有图片，实际从dao取
	private List<ImageInfo> getImageInfosBy() {
		List<ImageInfo> imageInfos = new ArrayList<ImageInfo>();
		File posters = new File("poster");
		File[] files = posters.listFiles();
		for(int i=0;i<files.length;i++) {
			if(files[i].isFile()) {
				String name = StringUtils.substringBeforeLast(files[i].getName(), "."); 
				ImageInfo imageInfo = new ImageInfo(String.valueOf(i),
						              name,files[i].getAbsolutePath());
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
				imageInfos.add(imageInfo);
			}
		}
		
		return imageInfos;
	}

	// 显示加载图片
	private void loadImages(final ImageViewerPanel imagePanel) {
		SwingWorker worker = new SwingWorker() {
				public Object construct() {
					List<ImageInfo> imageInfos = getImageInfosBy();
					return imageInfos;
				}
				public void finished() {
					loadImages(imagePanel,(List<ImageInfo>)get());
				}
			};
		worker.start();
	}
	
	
	private void loadImages(final ImageViewerPanel imagePanel,
			final List<ImageInfo> imageInfos) {

//		if (loadImageThread != null && loadImageThread.isAlive()) {// 存在加载图片的线程
//			synchronized (loadImageThread) {// 将其加入到同步块中
//				loadImageThread.interrupt();// 中断线程
//			}
//		}

		final JPanel imageBoxPanel = imagePanel.getImageBoxPanel();// 获得图片箱面板
		if (imageBoxPanel.getComponentCount() > 0) {// 如果图片箱不为空
			imageBoxPanel.removeAll();// 清空图片箱
		}

		if (imageInfos == null || imageInfos.isEmpty()) {// 如果图片为空
			imagePanel.validate();// 刷新面板

		} else {
			for (int i=0;i<imageInfos.size();i++) {
				imageBoxPanel.add(new ImagePreviewButton(imageInfos.get(i)));// 添加指定图片到图片箱
				imagePanel.validate();
			}
		}
	}	
	
	
	
	
	
	
	
	
	
	
	
	
	//最小化到托盘
	private void minimizeToTray() {
        try {
        	systemTray.add(trayIcon);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
	
	//关闭窗口
	private void thisWindowClosed(WindowEvent evt) {
		if (SystemTray.isSupported()) {  
			setVisible(false);  
            //minimizeToTray();  
        } else {  
        	exit(); 
        } 
	}

	//退出
	private void exit() {
		Database.close();
		System.exit(0);
		//playerPanel.exit();
	}
	
}
